package com.mcay.easyexcel.service.impl;

import com.mcay.easyexcel.dao.StudentDao;
import com.mcay.easyexcel.entity.Student;
import com.mcay.easyexcel.exception.ExcelException;
import com.mcay.easyexcel.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * Created by  longHe
 * 2021/8/20 18:54
 */
@Service
@Transactional
@Slf4j
public class StudentServiceImpl implements StudentService {

    private static final int INSERT_NUMBER = 200;

    @Autowired
    private StudentDao studentDao;


    @Override
    public List<Map<String, Object>> findeStudentPage(Map<String, String> map) {
        return studentDao.findStudentInfoByParam(map);
    }

    @Override
    public void batchInsertStudent(List<Student> studentList) {
        //非空判断
        if (studentList == null || studentList.isEmpty()) {
            throw new ExcelException("空指针异常！---> studentList is null,function is insertStudentTest", 500);
        }
        int listSize = studentList.size();
        int toIndex = INSERT_NUMBER;
        try {
            //分批插入数据库，INSERT_NUMBER：控制每批插入条数
            for (int i = 0; i < studentList.size(); i+=INSERT_NUMBER) {
                //最后一批toIndex控制
                if (i + INSERT_NUMBER > studentList.size()) toIndex = listSize -i;
                List<Student> newStudentList = studentList.subList(i, i + toIndex);
                studentDao.insertStudent(newStudentList);
            }
        } catch (Exception e) {
            log.error("批量插入失败！失败原因：{}", e.toString());
            e.printStackTrace();
        }

    }
}
